package cn.lblbc.album.adapter

import android.content.Intent
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
import cn.lblbc.album.R
import cn.lblbc.album.model.ImageItem
import com.bumptech.glide.Glide
import com.bumptech.glide.load.resource.bitmap.CenterCrop
import com.bumptech.glide.load.resource.bitmap.RoundedCorners
import com.bumptech.glide.request.RequestOptions

class ImageAdapter(private val images: List<ImageItem>) : 
    RecyclerView.Adapter<ImageAdapter.ImageViewHolder>() {
    
    class ImageViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
        val imageView: ImageView = itemView.findViewById(R.id.imageView)
        val nameTextView: TextView = itemView.findViewById(R.id.nameTextView)
        val dateTextView: TextView = itemView.findViewById(R.id.dateTextView)
    }
    
    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ImageViewHolder {
        val view = LayoutInflater.from(parent.context)
            .inflate(R.layout.item_image, parent, false)
        return ImageViewHolder(view)
    }
    
    override fun onBindViewHolder(holder: ImageViewHolder, position: Int) {
        val image = images[position]
        
        // 使用Glide加载图片，增加错误处理
        val requestOptions = RequestOptions()
            .transform(CenterCrop(), RoundedCorners(16))
            .placeholder(R.drawable.ic_placeholder)
            .error(R.drawable.ic_error)
        
        Glide.with(holder.itemView.context)
            .load(image.path)
            .apply(requestOptions)
            .into(holder.imageView)
        
        holder.nameTextView.text = image.name
        holder.dateTextView.text = formatDate(image.dateModified)
        
        // 设置点击事件，打开图片查看器
        holder.imageView.setOnClickListener {
            val context = holder.itemView.context
            val intent = Intent(context, cn.lblbc.album.ImageViewerActivity::class.java).apply {
                putExtra(cn.lblbc.album.ImageViewerActivity.EXTRA_IMAGE_LIST, ArrayList(images))
                putExtra(cn.lblbc.album.ImageViewerActivity.EXTRA_CURRENT_POSITION, position)
            }
            context.startActivity(intent)
        }
    }
    
    override fun getItemCount(): Int = images.size
    
    private fun formatDate(timestamp: Long): String {
        return try {
            val date = java.util.Date(timestamp * 1000)
            val formatter = java.text.SimpleDateFormat("yyyy-MM-dd HH:mm", java.util.Locale.getDefault())
            formatter.format(date)
        } catch (e: Exception) {
            "Unknown date"
        }
    }
}